const db=require('../dbConfig');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

// ---------------------不需要登录的---------------------

// 用户注册
let register=async (obj)=>{
  function randomString(len) {
    len = len || 32;
    let $chars = 'ABCDEFGHJKLMNOPQRSTUVWXYZabcdegfhijklmnoprstuvwxyz12345678';    /*默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1*/
    let maxPos = $chars.length;
    let pwd = '';
    for (i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  } 
  let userId=randomString(24);
  let {username,password,email}=obj;
  password= bcrypt.hashSync(password,10);
  let sql=`insert into user (id,name,password,email) values(?,?,?,?)`;
  let result = await db(sql,[userId,username,password,email]);
  return {success:true};
}

// 用户登录
let login=async (obj,flag)=>{
  let {username,password}=obj;
  let sql=`select id,password,name,role,email,is_show,phone,motto,avator,FROM_UNIXTIME(UNIX_TIMESTAMP(create_time), '%Y-%m-%d %H:%i:%s') create_time from user where BINARY name=? or BINARY email=? or phone=?`;
  let result = await db(sql,[username,username,username]);
  if(result.length==0){
     return{
      success:false,
      msg:'用户名不存在~~~'
    }
  }
  else{
    userPassword=result[0].password;
    const pwdMatchFlag=bcrypt.compareSync(password,userPassword);
    if(!pwdMatchFlag){
      return{
        success:false,
        msg:'密码错误~~~'
      }
    }
    else{
      delete result[0].password;
      // 过期时间                                         //一天
      let expireTime =Math.floor(Date.now() / 1000) + (24* 60 * 60);
      // 生成过期时间
      // withExpiresAt
      const token = jwt.sign({ userId: result[0].id,exp:expireTime},flag); 
      return{
        success:true,
        token:token,
        result:result[0]
      };
    }
  }
}

// 查询 用户名||邮箱||手机号 是否被使用
let checkInfo=async(obj)=>{
  let {type,info}=obj;
  let sql=`select count(*) count from user where ??=?`;
  let [{count}] = await db(sql,[type,info]);
  return { count:count };
}

function randomCode(count){
  let chars='0123456789';
  let str='';
  for(let i=0;i<count;i++){
    str+=chars.charAt(Math.floor(Math.random()*chars.length));
  }  
  return str;
}

// 发送验证码到邮箱
let sendCodeByEmail=async(obj)=>{
  let {type,contact}=obj;
  let sql=`select id from captcha where contact=?`;
  let [result]=await db(sql,[contact]);
  if(result){
    let del=`delete from captcha where contact=?`;
    await db(del,[contact]);
  }
  const nodemailer = require('nodemailer');
  let code=randomCode(6);
  console.log('验证码为：'+code);
  let title='';
  if(type==0) title='【SUK图床】你正在通过邮箱注册 SUK图床 账号，如非本人操作，请忽略此邮件。'; 
  else if(type==1) title='【SUK图床】你正在通过邮箱找回密码，如非本人操作，请忽略此邮件。'; 
  else title='【SUK图床】你正在更换绑定的邮箱，如非本人操作，请忽略此邮件。'; 
  // 实例化nodemailer对象
  let transporter = nodemailer.createTransport({
    service:'qq',
    secure: false,
    auth: {
      user: '3481355400',
      pass: 'nxvhppqqpwaschid'
      // 1030616193 lhzeyvupwugpbehg
    }
  });
  transporter.sendMail({
    from: '3481355400@qq.com',
    to: contact,
    subject: title,
    text:'本次请求的验证码为：'+code+'，验证码一分钟内有效，到期自动失效。'
  },
  async (err, data) => {
    if (err) {
      conso
      return{
        success: false,
        err
      };
    } 
    else {
      let sql=`insert into captcha (contact,code) values (?,?)`;
      await db(sql,[contact,code]);
    }
  })
  return {success:true};
}

// 发送验证码到手机
let sendCodeByPhone=async(obj)=>{
  let {type,contact}=obj;
  let sql=`select id from captcha where contact=?`;
  let [result]=await db(sql,[contact]);
  if(result){
    let del=`delete from captcha where contact=?`
    await db(del,[contact]);
  }
  let QcloudSms = require("qcloudsms_js");
  // 短信应用 SDK AppID
  let appid = 1400297900;  // SDK AppID 以1400开头
  // 短信应用 SDK AppKey
  let appkey = "fde793b391dd052c25d6d673c2bbadea";
  // 需要发送短信的手机号码
  // let phoneNumbers = ['18867791867'];
  let phoneNumbers=[contact];
  // 短信模板 ID，需要在短信控制台中申请
  let templateId;
  // let templateId = 511351;  // 登录  params的第二个参数是规定时间内如：1     NOTE: 这里的模板ID`7839`只是示例，真实的模板 ID 需要在短信控制台中申请
  // 505227;      //注册
  // 512249;      //找回密码
  // 516510       //绑定手机号
  // 516514       //修改绑定的手机号
  // 516704       //2020年祝福语
  if(type==0) templateId=505227;          //注册 
  else if(type==1) templateId=512249;     //找回密码
  else if(type==2) templateId=516510;     //绑定手机号
  else if(type==3) templateId=516514;     //修改绑定的手机号
  // 签名
  let smsSign = "众行则北京科技有限公司";  // NOTE: 签名参数使用的是`签名内容`，而不是`签名ID`。这里的签名"腾讯云"只是示例，真实的签名需要在短信控制台申请
  // 实例化 QcloudSms
  let qcloudsms = QcloudSms(appid, appkey);
  let ssender = qcloudsms.SmsSingleSender();
  let params = [randomCode(6)];
  ssender.sendWithParam("86", phoneNumbers[0], templateId,params, smsSign, "", "", callback); 
  // ssender.sendWithParam("86", phoneNumbers[0], templateId, smsSign, "", "", callback); 
  // 设置请求回调处理, 这里只是演示，用户需要自定义相应处理回调
  async function callback(err, reqData, resData) {
    if (err) {
      console.log("err: ", err);
      return {success:false };
    } 
    else {
      let code=reqData.req.body.params[0];
      let sql=`insert into captcha (contact,code) values (?,?)`;
      await db(sql,[contact,code]);
      return { success:true };
    }
  }
}

// 重置密码
let resetPassword=async(obj)=>{
  let {contact,password,type}=obj;
  password= bcrypt.hashSync(password,10);
  let sql='update user set password=? where ??=?';
  let {affectedRows} = await db(sql,[password,type,contact]);
  if(affectedRows>0) return {success:true};
  return {success:false};
}

// 检查验证码是否正确
let checkCode=async(obj)=>{
  let {code,contact}=obj;
  let sql=`select id from captcha where contact=? and code=?`;
  let [result]=await db(sql,[contact,code]);
  if(result) return { success:true };
  // let del=`delete from captcha where contact=?`
  // await db(del,[contact]);
  return { success:false };
}

// 删除验证码
let deleteCode=async(obj)=>{
  let {contact}=obj;
  let del=`delete from captcha where contact=?`;
  return db(del,[contact]);
}

// ---------------------需要登录的---------------------

// 修改头像
let updateAvator=async (obj,userId)=>{
  let {avator}=obj;
  let sql=`update user set avator=? where id=?`;
  return db(sql,[avator,userId]);
}

//用户  绑定||更换   邮箱 手机号 密码
let updateInfo=async (obj,userId)=>{
  let {info,type}=obj;
  let sql=`update user set ??=? where id=?`;
  return db(sql,[type,info,userId]);
}

// 修改个人信息
let byUpdate=async (obj,userId)=>{
  let {username,motto,password}=obj;
  let sql=`update user set name=? , motto=? where id=?`;
  let inserts=[username,motto,userId];
  if(password){
    sql=`update user set name=? , password=?,motto=? where id=?`;
    password= bcrypt.hashSync(password,10);
    inserts.splice(1,0,password);
  } 
  let result = await db(sql,inserts);
  if(result.errno) return {success:false,msg:'该用户名已经存在~~~~~'};
  return result;
}

// ---------------------管理员---------------------

// 获取所有用户列表
let _select=async (obj)=>{
	let data={};
	let {page,username}=obj;
	page = (page - 1) *10;
 	let arr=['%'+username+'%',page];
  let sql=`select id,name,role,email,avator,phone,motto,is_show,FROM_UNIXTIME(UNIX_TIMESTAMP(create_time), '%Y-%m-%d %H:%i:%s') create_time,FROM_UNIXTIME(UNIX_TIMESTAMP(update_time), '%Y-%m-%d %H:%i:%s') update_time 
    from user where name like ? order by case when is_show in (1) then 0 else 1 end,create_time LIMIT ?,10`;
  let result=await db(sql,arr);
  let sql2='select count(*) count from user where',arr2=[];
  sql2+=` name like ? `; 
  arr2.push('%'+username+'%'); 
  let count=await db(sql2,arr2);
  data.count=count[0].count;
  data.result=result;
	return data;
}


// 恢复/禁用某用户
let _update=async(obj)=>{
 	let {isShow,id}=obj;
  let sql=`update user set is_show=? where id=?`;
  return db(sql,[isShow,id]);
}

// 批量删除用户
let _delete=async(id)=>{
  id=id.join(',');
  let sql=`delete from user where FIND_IN_SET(id,?)`;
  return db(sql,[id]);
}

module.exports={
  // noLogin
  login,register,checkInfo,sendCodeByEmail,sendCodeByPhone,resetPassword,checkCode,deleteCode,
  // mustLogin
  updateAvator,byUpdate,updateInfo,
  // admin
	_select,_update,_delete
}